import { defineStore } from "pinia";
import { ref } from "vue";
import { RouteLocationNormalized } from "vue-router";
export interface ITagsView extends Partial<RouteLocationNormalized> {
  title?: string;
}
export const useTagsViewStore = defineStore("tagsview", () => {
  const tagsViewList = ref<ITagsView[]>([]);

  // 新增
  function addTagsView(tagsview: ITagsView) {
    // 已存在return
    if (tagsViewList.value.some((item) => item.path === tagsview.path)) return;
    tagsViewList.value.push({ ...tagsview, title: tagsview.meta.title });
  }

  // 删除
  function removeTagsView(tagsview: ITagsView) {
    return new Promise((resolve, reject) => {
      const findIndex = tagsViewList.value.findIndex(
        (item) => item.path === tagsview.path
      );
      if (findIndex > -1) {
        tagsViewList.value.splice(findIndex, 1);
        resolve();
      }
    });
  }

  /**
   * 删除右侧tagview
   */
  function closeRightTag(idx: number) {
    return new Promise((resolve, reject) => {
      tagsViewList.value = tagsViewList.value.filter(
        (item, index) => index <= idx
      );
      resolve();
    });
  }

  /**
   * 删除其他tagview
   */
  function closeOtherTag(idx) {
    return new Promise((resolve, reject) => {
      tagsViewList.value = tagsViewList.value.filter(
        (item, index) => index === idx
      );
      resolve();
    });
  }

  return {
    tagsViewList,
    addTagsView,
    removeTagsView,
    closeRightTag,
    closeOtherTag,
  };
});
